import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLEditorKit;


public class BrowserFrame extends JFrame implements ActionListener, HyperlinkListener  {
	
	private static final long serialVersionUID = 4298082556398454722L;
	
	private JEditorPane pane = new JEditorPane();
	private JTextField addressField = new JTextField();
	private File file = new File("start.htm");
	
	private HTMLEditorKit editorKit = new MyHTMLEditorKit();
	
	public BrowserFrame() {
		init();
		try {
			pane.setPage("file:/"+file.getCanonicalPath());
		} catch (IOException e) {
			try {
				file = new File("error.htm");
				pane.setPage("file:/"+file.getCanonicalPath());
			} catch (IOException e1) {
				System.out.println("no error file found");
			}
		}
		pane.addHyperlinkListener(this);
	}
	
	private void init(){
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    	setTitle("Browser");

    	pane.setEditorKit(editorKit);
		pane.setEditorKitForContentType("HTML", editorKit);
    	pane.setEditable(false);
		JScrollPane browserScrollPane = new JScrollPane(pane);
		
		addressField.addActionListener(this);
		
		Container contentPane = getContentPane();
		contentPane.add(addressField, BorderLayout.PAGE_START);
		contentPane.add(browserScrollPane, BorderLayout.CENTER);
		
        pack();
        setSize(600,400);
        setVisible(true);
	}
	
	void openFile(String addr) {
		if(addr!=null) file = new File(addr);
		try {
			try {
				URL url = new URL(addr);
				pane.setPage(url.toString());
			} catch (MalformedURLException e1) {
				pane.setPage("file:/"+file.getCanonicalPath());
			}
		} catch (IOException e) {
			try {
				file = new File("error.htm");
				pane.setPage("file:/"+file.getCanonicalPath());
			} catch (IOException e1) {
				System.out.println("no error file found");
			}
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String addr = addressField.getText();
		openFile(addr);
	}

	@Override
	public void hyperlinkUpdate(HyperlinkEvent e) {
	    HyperlinkEvent.EventType type = e.getEventType();
	    if (type == HyperlinkEvent.EventType.ACTIVATED) {
	      try {
	    	  addressField.setText(e.getURL().toString());
	    	  pane.setPage(e.getURL());
	      }
	      catch (Exception e1) {
	    	  e1.printStackTrace();
	      }
	    }	
	}

}